define(function(require, exports){
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var popwin	= require('@base/dialog').base;
	var util	= require('util');

	var Product = popwin.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'title': LANG('选择产品'),
				'class': 'P-product',
				'id': null,
				'silence': false,
				'size': 'l',
				'isSingle': false, // 是否单选，默认多选
				'view_model': {
					'isAddMode': false
					,'showSelected': false
					,'showSelect': this.showSelect
				}
			});

			this.$data = {};
			this.Super('init', arguments);
		},
		afterBuild:function(){
			this.Super('afterBuild',arguments);
			var el = this.getDOM('body');
			var cls = this.getConfig('class');
			el.addClass(cls);
			el.append($([
				'<div class="selectProductWrap">',
					'<div class="selectivePage" ms-visible="!isAddMode">',
						'<div class="headerBtn">',
							'<div class="addBtn fr" pub-name="add" pub-mod="@base/common/input.button" ></div>',
							'<div class="selected fr mr30">',
								'<label for="showselect" class="cur_p">',
									'<input id="showselect" type="checkbox" ms-duplex-radio="showSelected" ms-click="showSelect()"/>',
									'<span>' + LANG('显示已选') + '</span>',
								'</label>',
							'</div>',
						'</div> ',
						'<div class="porgrid" pub-name="grid" pub-mod="product/grid/product.selectList"></div>',
					'</div>',

					'<div class="addedPage" ms-visible="isAddMode">',
						'<div class="animated" >',
							'<div pub-name="productForm" pub-mod="product/action/edit.main"></div>',
						'</div>',
					'</div>',
				'</div>'
			].join('')));

			this.$animate = el.find('.animated');

			var config = {
				'add': {
					'width': 0,
					'value': LANG('新建产品'),
					'class': 'btn btn-primary'
				},
				'grid': {
					'operation': {
						width: 140
						,render: this.renderOperation.bind(this)
					}
					,'hasRefresh':false
					,'hasSearch': true
					,'pager': {'size':10, 'showSizeTypes':0}
					,'list': {
						'rowSelect': true,
						'rowSelectOp': true
					}
				},
				'productForm': {
					'showButton': false
				}
			};

			this.buildFromTemplate(config);
		},
		afterBuildTemplate: function(){
		},
		showSelect: function(){
			var ids;
			if(this.vm.$.showSelected){
				ids = util.keys(this.$data, function(key){
					return +key;
				});
				ids = ids.join(',');
			}
			this.$.grid.setParam({ids: ids});
			this.$.grid.reload();
		},
		renderOperation:function(index,val,row){
			var id = +row['_id'];
			var cls = 'btn btn-default';
			var title = LANG('添加');
			if(this.$data[id]){
				cls = 'btn btn-success';
				title = LANG('取消');
			}
			return '<input data-op="select" type="button" class="'+ cls +'" value="'+title+'" />';
		},
		onListOpClick: function(ev){
			var dom	= ev.param.el;
			var data = ev.param.data;
			var id	= +ev.param.data._id;
			//添加
			if(dom.hasClass('btn-default')){
				dom.removeClass('btn-default').addClass('btn-success').val(LANG('取消'));
			}
			//删除
			else {
				dom.removeClass('btn-success').addClass('btn-default').val(LANG('添加'));
			}

			if(!this.$data[id]){
				this.$data[id] = data;
				this.fire('selectProduct', {data: data});
			}
			else {
				delete this.$data[id];
				this.fire('unselectProduct', {id: id});
				this.send(this.parent(), 'removeItem', {id: id});
			}
			return false;
		},
		getValue: function(){
			return this.$data;
		},
		setValue: function(data) {
			var self = this;
			self.$data = {};
			util.each(data, function(item) {
				self.$data[item._id] = item;
			});
			return self;
		},
		onInputClick: function(ev){
			var vm =  this.vm.$;
			var self =  this;
			if(ev.name === "buttonOk"  && vm.isAddMode){
				//添加产品模式下点击完成
				if(ev.name === 'buttonOk'){
					self.$.productForm.save();
				} else {
					self.$.productForm.reset();
				}
				return false;
			}

			this.Super('onInputClick', arguments);
			if(ev.from === this.$.add){
				this.switchMode('add');
			}
			this.update();
		},
		onRemoveItem: function(ev){
			var id = +ev.param.id;
			if(this.$data[id]){
				delete this.$data[id];
			}
		},
		onSaveProductSuccess: function(ev){
			//新建创意包页面
			this.onCancel();
			var data = ev.param.data;
			this.$data[data._id] = data;
			this.fire('selectProduct', {data: data});
			return false;
		},
		switchMode: function(mode){
			var self	= this;
			var vm		= self.vm.$;
			switch (mode){
				case 'list':
					this.$.grid.reload();
					// 动画效果-移出
					this.$animate.animate({'left':'1035px'}, 500, function(){
						vm.isAddMode = false;
					});
					// // 更新标题名字
					this.setTitle(LANG('选择产品'));


					break;
				case 'add':
					vm.isAddMode = true;
					self.$.productForm.reset();

					// 动画效果-移进
					this.$animate.animate({'left':'15px'}, 500, function(){
					});

					// 更新标题名称
					this.setTitle(LANG('新建产品'));

					break;
				default:
					return false;
			}
			return true;
		},
		onCancel: function(){
			//新建创意包页面
			var vm = this.vm.$;
			if(vm.isAddMode){
				//重置到选择创意包页面
				this.switchMode('list');
				this.$.grid.load();
			}
			else {
				this.hide();
			}
			return false;
		},
		validate: function(data){
			var isSingle = this.getConfig('isSingle');
			if (isSingle && Object.getOwnPropertyNames(data).length > 1 ) {
				return false;
			}
			else {
				return true;
			}
		},
		onOk: function() {
			var value = this.getValue();
			if (this.validate(value)) {
				this.hide();
				this.fire('selectProductOk', this.getValue());
			}
			else {
				pubjs.alert('一个落地页只能关联一个产品');
			}
		},
		reload: function(){
			this.$.grid.reload();
			return this;
		}
	});
	exports.base = Product;


	// 批量导入 弹窗
	var BatchAddPop = popwin.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'title': LANG('产品批量导入'),
				'size': 'm',
				'view_model':{
					'ids': ''
				}
			});

			this.$data = null;
			this.$error = false;

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);

			var el = self.getDOM('body');
			self.$textarea = $([
				'<textarea class="h200 w90pct mr10 mt10" ms-duplex="ids" placeholder="'+ LANG('多个id使用 ; 或换行隔开') + '"></textarea>'
			].join('')).appendTo(el);

		},
		onOk: function(ev){
			var self = this;
			var data = self.getData();

			if(!data.length){
				pubjs.alert(LANG('请输入id'), function(){
					self.$textarea.focus();
				});
				return false;
			}

			pubjs.mc.send('product/batchAdd', {
					'ids': data
				},
				self.onBatchAdd.bind(self)
			);

			self.hide();
			return false;
		},
		onBatchAdd: function(err, data){
			if(err) {
				pubjs.alert(err.message);
				return false;
			}
			pubjs.alert('设置成功');
			this.fire('batchAddProductSuccess', data);
		},
		reset: function(){
			var self = this;
			self.$error = false;
			self.vm.reset();
			return self;
		},
		getData: function(){
			var self = this;
			self.$error = false; // 还原错误标记
			var vm = self.vm.$;
			// 重新处理一下ids
			var ids = [];
			util.each(vm['ids'].replace(/(\n)+|(\r\n)+|(；)+|(;)/g, '\n').split('\n'), function(item){
				var id = util.trim(item);
				if(id){
					ids.push(id);
				}
			});
			return util.unique(ids);
		}
	});
	exports.batchAddPop = BatchAddPop;
});